package com.byx.chatclient.entity;

import android.util.Log;

import androidx.annotation.NonNull;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * ResultCallback
 * 使用{@link Result}作为响应结果的{@link Callback}的基本实现类，
 * 封装了对{@link Callback#onResponse(Call, Response)}中{@link Response}的一些判断,减少重复代码
 * @author Superb
 * @date 2021/5/2 21:26
 */
public abstract class ResultCallback<T> implements Callback<Result<T>> {
    private static final String TAG = "ResultCallback";
    /**
     * Invoked for a received HTTP response.
     *
     * <p>Note: An HTTP response may still indicate an application-level failure such as a 404 or 500.
     * Call {@link Response#isSuccessful()} to determine if the response indicates success.
     *  @param call
     * @param response
     */
    @Override
    public void onResponse(@NonNull Call<Result<T>> call, @NonNull Response<Result<T>> response) {
        if (response.isSuccessful()){
            Result<T> result = response.body();
            if (result != null){
                if (result.getCode().equals(ResultCode.SUCCESS.code())) {
                    onResultSuccess(result.getData());
                }else {
                    Log.e(TAG, "onResponse: The server return an error :\ncode:" +
                            result.getCode() + ",msg:" + result.getData());
                    onResultFailure(result.getCode(),result.getMessage());
                }
            }
        }else {
            onResponseError(response.code(), response.message());
        }
    }

    /**
     * Invoked when a network exception occurred talking to the server or when an unexpected exception
     * occurred creating the request or processing the response.
     *  @param call
     * @param t
     */
    @Override
    public void onFailure(@NonNull Call<Result<T>> call, @NonNull Throwable t) {
        onException(call, t);
    }

    /**
     * Invoked for a received HTTP response.
     *
     * <p>Note: An HTTP response may still indicate an application-level failure such as a 404 or 500.
     *
     * 响应错误
     * @param code 错误码
     * @param msg 错误信息
     */
    public void onResponseError(int code, String msg){
        Log.e(TAG, "onResponseError: " + "code:" + code + "msg:" + msg);
    }

    /**
     * 用户请求的操作成功
     * @param data 返回数据 {@link Result# data}
     */
    public abstract void onResultSuccess(T data);

    /**
     * 用户请求的操作失败
     * @param code {@link Result# code} 失败码
     * @param msg {@link Result# message} 失败信息
     */
    public abstract void onResultFailure(int code, String msg);

    /**
     * Invoked when a network exception occurred talking to the server or when an unexpected exception
     * occurred creating the request or processing the response.
     * @param call
     * @param t
     */
    public void onException(@NonNull Call<Result<T>> call, @NonNull Throwable t){
        Log.e(TAG, "onException: ", t);
    }
}
